//
//  ImagePickerManager.m
//  KingSelected
//
//  Created by 杨鹏 on 2023/10/28.
//

#import "ImagePickerManager.h"
#import <MobileCoreServices/MobileCoreServices.h>
#import <AVFoundation/AVFoundation.h>
#import <Photos/Photos.h>

@implementation ImagePickerManager

- (UIImagePickerController *)imagePickerControllerWithSourceType:(UIImagePickerControllerSourceType)sourceType {
    if (![UIImagePickerController isSourceTypeAvailable:sourceType]) {
        return nil;
    }
    
    UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
    imagePickerController.allowsEditing = YES;
    imagePickerController.delegate = self;
    imagePickerController.sourceType = sourceType;
    imagePickerController.mediaTypes = @[(NSString *)kUTTypeImage];
    imagePickerController.navigationBar.translucent = NO;
    imagePickerController.modalPresentationStyle = UIModalPresentationFullScreen;
    
    return imagePickerController;
}

- (void)showPickInVC:(UIViewController *)vc sourceType:(UIImagePickerControllerSourceType)sourceType completion:(ImagePickBlock)completion {
    if (!vc) {
        vc = [UIViewController getCurrentViewController];
    }
    UIImagePickerController *imagePicker = [self imagePickerControllerWithSourceType:sourceType];
    if (imagePicker) {
        self.pickBlock = completion;
        [vc presentViewController:imagePicker animated:YES completion:nil];
        [self privacyAuthorizationStateWithSourceType:sourceType showAlertIn:imagePicker];
    }
}
- (void)showNoEditPickInVC:(UIViewController *)vc sourceType:(UIImagePickerControllerSourceType)sourceType completion:(ImagePickBlock)completion {
    if (!vc) {
        vc = [UIViewController getCurrentViewController];
    }
    UIImagePickerController *imagePicker = [self imagePickerControllerWithSourceType:sourceType];
    imagePicker.allowsEditing = NO;
    if (imagePicker) {
        self.pickBlock = completion;
        [vc presentViewController:imagePicker animated:YES completion:nil];
        [self privacyAuthorizationStateWithSourceType:sourceType showAlertIn:imagePicker];
    }
}

- (void)privacyAuthorizationStateWithSourceType:(UIImagePickerControllerSourceType)sourceType showAlertIn:(UIViewController *)controller {
    if (sourceType == UIImagePickerControllerSourceTypeCamera) {
        if (![self authorizationStatusForMediaTypeCamera]) {
            [UIAlertController showAlertInViewController:controller withTitle:@"请打开相机权限" message:@"打开相机权限,可以上传您的照片" cancelButtonTitle:@"取消" destructiveButtonTitle:@"去设置" otherButtonTitles:@[] tapBlock:^(UIAlertAction *action, NSInteger buttonIndex) {
                if (buttonIndex == UIAlertControllerBlocksDestructiveButtonIndex) {
                    [self openSetting];
                }
            }];
        }
    }
    else if (sourceType == UIImagePickerControllerSourceTypePhotoLibrary) {
        if (![self authorizationStatusForPhotoLibrary]) {
            [UIAlertController showAlertInViewController:controller withTitle:@"请打开相册权限" message:@"打开相册权限,可以上传您的照片" cancelButtonTitle:@"取消" destructiveButtonTitle:@"去设置" otherButtonTitles:@[] tapBlock:^(UIAlertAction *action, NSInteger buttonIndex) {
                if (buttonIndex == UIAlertControllerBlocksDestructiveButtonIndex) {
                    [self openSetting];
                }
            }];
        }
    }
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    UIImage *img = info[picker.allowsEditing ? UIImagePickerControllerEditedImage : UIImagePickerControllerOriginalImage];
    [picker dismissViewControllerAnimated:YES completion:^{
        if (self.pickBlock) {
            self.pickBlock(img);
        }
        self.pickBlock = nil;
    }];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:^{
        self.pickBlock = nil;
    }];
}

- (void)uploadImage:(UIImage *)img success:(void (^)(id responseObject))success failure:(void (^)(NSError *error))failure {
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSData *imgData = [img compressWithMaxLength];
        [NetManager uploadWithURL:URL(@"common/uploadPic") parameters:nil fileData:@[imgData] fileNames:@[@"file"] mimeType:nil progress:nil success:^(id  _Nullable responseObject) {
            if (success) {
                success(responseObject);
            }
        } failure:^(NSError * _Nonnull error) {
            if (failure) {
                failure(error);
            }
        }];
    });
}

- (void)uploadImages:(NSArray *)imgs success:(void (^)(id responseObject))success failure:(void (^)(NSError *error))failure {
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSMutableArray *imgDatas = [[NSMutableArray alloc] init];
        for (UIImage *img in imgs) {
            NSData *imgData = [img compressWithMaxLength];
            [imgDatas addObject:imgData];
        }
        [NetManager uploadWithURL:URL(@"common/uploadPic") parameters:nil fileData:imgDatas fileNames:nil mimeType:nil progress:nil success:^(id  _Nullable responseObject) {
            if (success) {
                success(responseObject);
            }
        } failure:^(NSError * _Nonnull error) {
            if (failure) {
                failure(error);
            }
        }];
    });
}

- (BOOL)authorizationStatusForMediaTypeCamera {
    return [self authorizationStatusForMediaType:AVMediaTypeVideo];
}

- (BOOL)authorizationStatusForMediaType:(AVMediaType)mediaType {
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:mediaType];
    if (authStatus ==AVAuthorizationStatusRestricted || authStatus ==AVAuthorizationStatusDenied) {
        return NO;
    }
    
    return YES;
}

- (BOOL)authorizationStatusForPhotoLibrary {
    PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
    if (status == PHAuthorizationStatusRestricted || status == PHAuthorizationStatusDenied) {
        return NO;
    }
    return YES;
}

- (void)openSetting {
    NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
    if ([[UIApplication sharedApplication]canOpenURL:url]) {
        [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:nil];
    }
}

@end
